package xdu.lz.stage2_design_pattern.chapter5_reader_writer_pattern;

import java.util.Arrays;

//封装数据读写方法
public class ShareData {

    //存放数据
    private final char[] buffer;

    //读写锁实例
    private final ReadWriteLock lock = new ReadWriteLock();

    //初始化数据
    public ShareData(int size) {
        this.buffer = new char[size];
        for (int i = 0; i < size; i++) {
            buffer[i] = '*';
        }
    }

    //读数据
    public char[] read() throws InterruptedException {
        try {
            //获取读锁，读数据
            lock.readLock();
            return this.doRead();
        } finally {
            //释放读锁
            lock.readUnLock();
        }

    }

    //写数据
    public void write(char c) throws InterruptedException {
        try {
            //获取写锁
            lock.writeLock();
            //写数据
            this.doWrite(c);
        } finally {
            //释放写锁
            lock.writeUnLock();
        }

    }


    private char[] doRead() {
        char[] copyChar = Arrays.copyOf(buffer, buffer.length);
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return copyChar;
    }

    private void doWrite(char c) {
        for (int i = 0; i < buffer.length; i++) {
            buffer[i] = c;
        }
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
